package day06;

import java.io.*;

/*
@Author: 王少杰
@Date: 2025/1/6
@Time: 14:45
@FileName: Demo04.java
@描述:
文件读写 40多个类
        open read write close

        文件读写是从如下几个类继承的:
        InputStream/OutputStream 字节流，一次读写一个字节
        Reader/Write             字符流，一次读写一个字符
        上述用法差不多，就是单位不一样

        读文件
        readByByte(String path)
        readByChar(String path)
        写文件
        writeByByte(String path,String content)
        writeByByte(string path,String content)

File类:文件、目录的一个类
*/
public class Demo04 {
    public static void main(String[] args) throws IOException {
        File file = new File("E:\\Java项目\\Project\\LearnJava\\src\\day04\\Demo01.java");
        File file1 = new File("E:\\Java项目\\Project\\LearnJava\\src\\day06\\abc.java");
        System.out.println(file.isFile());
        System.out.println(file.isDirectory());

//        if (!file1.isFile()) {
//            file1.createNewFile();//新建文件
//        }

        try {
            boolean isSuccess = file.createNewFile();
            System.out.println("新建文件:" + isSuccess);
            System.out.println("最后的修改时间:" + file1.lastModified());
            System.out.println("文件名:" + file1.getName());
            System.out.println("写权限:" + file1.canWrite());

        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }

        System.out.println("删除文件:" + file1.delete());

        readByByte("E:\\Java项目\\Project\\LearnJava\\src\\day06\\Demo01.java");
        readByChar("E:\\Java项目\\Project\\LearnJava\\src\\day06\\Demo02.java");
        writeByChar("e:\\a.txt","今天星期一。\n");
        writeByByte("e:\\a.txt","天气不错。\n");
    }

    public static void readByByte(String path) throws IOException {
        //创建一个对象
        FileInputStream fileInputStream = new FileInputStream(path);
        //读文件
        int c = 0;
        while (c != -1){
            c = fileInputStream.read();
            System.out.write(c);//一次打印一个字节
        }
        //关闭对象
        fileInputStream.close();
    }

    public static void readByChar(String path) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(path);
        int c = 0;
        while (c != -1){
            c = fileInputStream.read();
            System.out.write((char)c);//打印一个字符
        }
        fileInputStream.close();
    }

    //BufferedReader 一次读取一行
    //BufferedWrite
    //设置文件编码方式为utf-8
    //追加写，怎么处理?
    //File 拓展其他方法

    public static void writeByChar(String path,String content) throws IOException {
        FileWriter fileWriter = new FileWriter(path);
        fileWriter.write(content);
        fileWriter.close();
    }

    public static void writeByByte(String path,String content) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream(path);
        fileOutputStream.write(content.getBytes());
        fileOutputStream.close();
    }
}
